Rotate list

Time: O(N); Space: O(1); medium

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: {ListNode} 1->2->3->4->5->None, k = 2

Output: {ListNode} 4->5->1->2->3->None

Explanation:

  • rotate 1 steps to the right: 5->1->2->3->4->None

  • rotate 2 steps to the right: 4->5->1->2->3->None

Example 2:

Input: {ListNode} 0->1->2->None, k = 4

Output: {ListNode} 2->0->1->None

Explanation:

  • rotate 1 steps to the right: 2->0->1->None

  • rotate 2 steps to the right: 1->2->0->None

  • rotate 3 steps to the right: 0->1->2->None

  • rotate 4 steps to the right: 2->0->1->None

[1]:
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

    def __repr__(self):
        if self:
            return "{} -> {}".format(self.val, repr(self.next))
[2]:
class Solution1(object):
    """
    Time: O(N)
    Space: O(1)
    """
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or not head.next:
            return head

        n, cur = 1, head
        while cur.next:
            cur = cur.next
            n += 1
        cur.next = head

        cur, tail = head, cur
        for _ in range(n - k % n):
            tail = cur
            cur = cur.next
        tail.next = None

        return cur
[3]:
s = Solution1()

head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(3)
head.next.next.next.next = ListNode(4)
head.next.next.next.next.next = ListNode(5)
k = 2
res = s.rotateRight(head, k)
exp = [4,5,1,2,3]
for val in exp:
    assert res.val == val
    res = res.next

head = ListNode(0)
head.next = ListNode(1)
head.next.next = ListNode(2)
k = 4
res = s.rotateRight(head, k)
exp = [2,0,1]
for val in exp:
    assert res.val == val
    res = res.next